<template>
  <div class="body_all">
    <div class="ba_top">
      <div>
        <el-select
          size="small"
          v-model="searchList.year"
          filterable
          allow-create
          default-first-option
          placeholder="年度"
        >
          <el-option
            v-for="item in yearsList"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button
          style="margin-left: 8px"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="btnSearch"
          >搜索</el-button
        >
        <el-button
          type="refresh"
          icon="el-icon-refresh"
          @click="btnRefresh"
          size="mini"
          >重置</el-button
        >
      </div>
      <div style="margin-top: 8px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="showEditer(0)"
          >新增销售目标</el-button
        >
      </div>
    </div>
    <div class="ba_main">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="员工目标" name="offline">
          <el-button
            :type="offlineType == 0 ? 'primary' : ''"
            size="mini"
            @click="
              offlineType = 0;
              tableKey = !tableKey;
            "
            >目标</el-button
          >
          <el-button
            :type="offlineType == 1 ? 'primary' : ''"
            size="mini"
            @click="
              offlineType = 1;
              tableKey = !tableKey;
            "
            >业绩</el-button
          >
        </el-tab-pane>
        <el-tab-pane plain label="部门目标" name="quit"></el-tab-pane>
      </el-tabs>
      <el-table
        v-loading="loading"
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        show-summary
        :summary-method="getSummaries"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column v-if="activeName=='offline'" prop="name" label="员工姓名" flex="left">
        </el-table-column>
        <el-table-column v-else prop="department_name" label="部门名称" flex="left">
        </el-table-column>
        <!-- <el-table-column prop="date" label="员工部门"> </el-table-column> -->
        <!-- <el-table-column prop="name" label="考核时间"> </el-table-column> -->
        <!-- <el-table-column
          prop="address"
          label="总目标(元)"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month1"
          label="1月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement1" label="1月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  1,
                  scope.row.month1_id,
                  scope.row.achievement1
                )
              "
              >{{ scope.row.achievement1 }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month2"
          label="2月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement2" label="2月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  2,
                  scope.row.month2_id,
                  scope.row.achievement2
                )
              "
              >{{ scope.row.achievement2 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month3"
          label="3月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement3" label="3月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  3,
                  scope.row.month3_id,
                  scope.row.achievement3
                )
              "
              >{{ scope.row.achievement3 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month4"
          label="4月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement4" label="4月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  4,
                  scope.row.month4_id,
                  scope.row.achievement4
                )
              "
              >{{ scope.row.achievement4 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month5"
          label="5月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement5" label="5月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  5,
                  scope.row.month5_id,
                  scope.row.achievement5
                )
              "
              >{{ scope.row.achievement5 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month6"
          label="6月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement6" label="6月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  6,
                  scope.row.month6_id,
                  scope.row.achievement6
                )
              "
              >{{ scope.row.achievement6 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month7"
          label="7月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement7" label="7月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  7,
                  scope.row.month7_id,
                  scope.row.achievement7
                )
              "
              >{{ scope.row.achievement7 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month8"
          label="8月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement8" label="8月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  8,
                  scope.row.month8_id,
                  scope.row.achievement8
                )
              "
              >{{ scope.row.achievement8 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month9"
          label="9月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement9" label="9月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  9,
                  scope.row.month9_id,
                  scope.row.achievement9
                )
              "
              >{{ scope.row.achievement9 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month10"
          label="10月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement10" label="10月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  10,
                  scope.row.month10_id,
                  scope.row.achievement10
                )
              "
              >{{ scope.row.achievement10 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month11"
          label="11月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement11" label="11月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  11,
                  scope.row.month11_id,
                  scope.row.achievement11
                )
              "
              >{{ scope.row.achievement11 }}</span
            >
          </template></el-table-column
        >
        <el-table-column
          v-if="offlineType == 0 || activeName == 'quit'"
          prop="month12"
          label="12月(元)"
        >
        </el-table-column>
        <el-table-column v-else prop="achievement12" label="12月(元)">
          <template slot-scope="scope">
            <span
              class="edit_btn"
              @click="
                editor_achievement(
                  12,
                  scope.row.month12_id,
                  scope.row.achievement12
                )
              "
              >{{ scope.row.achievement12 }}</span
            >
          </template></el-table-column
        >
      </el-table>
      <div class="footerPage">
        <i class="el-icon-arrow-left"></i>
        <i class="el-icon-arrow-right"></i>
      </div>
      <!-- 新增编辑 -->
      <el-dialog
        :title="titleSource"
        :close-on-click-modal="false"
        :visible.sync="editorShow"
        width="45%"
        :close-on-press-escape="false"
      >
        <div class="dialogDiv">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="150px"
            class="demo-ruleForm"
          >
            <el-form-item label="考核年度" prop="year">
              <el-date-picker
                v-model="ruleForm.year"
                type="year"
                value-format="yyyy"
                placeholder="选择年"
              >
              </el-date-picker>
              <!-- <el-date-picker
                v-model="ruleForm.year"
                value-format="yyyy"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker> -->
            </el-form-item>
            <el-form-item label="目标类型" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择">
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.type == 2"
              label="部门"
              prop="department_id"
            >
              <el-select
                v-model="ruleForm.department_id"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="月度目标">
              <div v-for="(item, index) in ruleForm.target">
                <div class="ball">
                  <span>{{ item.month }}月目标</span>
                  <el-input
                    style="width: 60%"
                    v-model="item.t_amount"
                    placeholder="请输入金额（元）"
                  ></el-input>
                  <span>元</span>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="foot_btn">
          <el-button @click="resetGh('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitGh('ruleForm')"
            >提交</el-button
          >
        </div>
      </el-dialog>
      <!-- 修改业绩对话框 -->
      <el-dialog
        title="修改业绩"
        :close-on-click-modal="false"
        :visible.sync="achView"
        width="45%"
        :close-on-press-escape="false"
      >
        <div class="dialogDiv">
          <el-form
            :model="achData"
            :rules="achrules"
            ref="achData"
            label-width="150px"
            class="demo-ruleForm"
          >
            <el-form-item :label="achMonth + '月业绩(元)'" prop="amount">
              <el-input
                v-model="achData.amount"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="foot_btn">
          <el-button @click="resetAch('achData')">取消</el-button>
          <el-button type="primary" @click="submitAch('achData')"
            >提交</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      dialogEditer: false,
      // 搜索条件
      searchList: {
        type: "1", // 1.个人目标 2.部门目标
        year: "",
      },
      activeName: "offline",
      typeList: [
        {
          label: "个人目标",
          value: 1,
        },
        {
          label: "部门目标",
          value: 2,
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      ruleForm: {
        year: "",
        department_id: "", // 部门id
        type: 1, // 1：个人目标 2.部门目标
        target: [
          {
            month: 1,
            t_amount: 0,
          },
          {
            month: 2,
            t_amount: 0,
          },
          {
            month: 3,
            t_amount: 0,
          },
          {
            month: 4,
            t_amount: 0,
          },
          {
            month: 5,
            t_amount: 0,
          },
          {
            month: 6,
            t_amount: 0,
          },
          {
            month: 7,
            t_amount: 0,
          },
          {
            month: 8,
            t_amount: 0,
          },
          {
            month: 9,
            t_amount: 0,
          },
          {
            month: 10,
            t_amount: 0,
          },
          {
            month: 11,
            t_amount: 0,
          },
          {
            month: 12,
            t_amount: 0,
          },
        ], // 目标的json数组
      },
      rules: {
        year: [
          { required: true, message: "请选择考核时间", trigger: "change" },
        ],
        department_id: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择目标类型", trigger: "change" },
        ],
      },
      tableKey: true,
      yearsList: [], // 年度下拉数据
      // 线下公海-类型
      offlineType: 0,
      departmentList: [], // 部门下拉数据
      tableData: [],
      editorShow: false, // 对话框状态
      titleSource: "", // 对话框标题
      // 业绩数据
      achMonth: "",
      achData: {
        id: "",
        amount: "",
      },
      achrules: {
        amount: [
          { required: true, message: "请填写业绩金额", trigger: "change" },
        ],
      },
      achView: false, // 修改业绩数据的对话框
    };
  },
  created() {
    this.loading = true;
    this.getData();
    this.getdepartment();
    this.initYears();
  },
  methods: {
    // 更改业绩数据
    editor_achievement(month, id, value) {
      if (id == "") {
        this.$message({
          message: "该业绩未指定目标，不可操作",
          type: "warning",
        });
      } else {
        this.achMonth = month;
        this.achData.id = id;
        this.achData.amount = value;
        this.achView = true;
        console.log("点击的业绩月份", this.achData);
      }
    },
    // 切换目标卡
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.searchList.type = parseInt(tab.index) + 1;
      this.tableKey = !this.tableKey;
      this.btnSearch();
    },
    //设置日期列表
    initYears() {
      var myDate = new Date();
      var year = myDate.getFullYear(); //获取当前年
      this.initSelectYear(year);
    },
    initSelectYear(year) {
      this.yearsList = [];
      for (let i = 0; i < 30; i++) {
        this.yearsList.push({ value: year - i, label: year - i });
      }
      this.searchList.year = this.yearsList[0].value;
    },
    // 查询数据列表
    getData() {
      this.$cmsapi.salesTarget(this.searchList).then(
        (res) => {
          if (res.code == 0) {
            for (let i = 0; i < res.data.length; i++) {
              // 空转为''
              for (const key in res.data[i]) {
                if (!res.data[i][key] && res.data[i][key] !== 0) {
                  res.data[i][key] = "";
                }
              }
              // 将月份目标处理至prop直接使用数据-方便后面汇总数据使用
              for (let j = 1; j <= 12; j++) {
                let p_m = 0;
                // 目标
                for (let k = 0; k < res.data[i].target.length; k++) {
                  if (res.data[i].target[k].month == j) {
                    p_m = res.data[i].target[k].t_amount;
                  }
                }
                let jz = "month" + j;
                res.data[i][jz] = p_m;
                // 业绩
                let p_y = 0;
                let p_id = ""; // 业绩id
                for (let k = 0; k < res.data[i].target.length; k++) {
                  if (res.data[i].target[k].month == j) {
                    p_y = res.data[i].target[k].c_amount;
                    p_id = res.data[i].target[k].id;
                  }
                }
                let yj = "achievement" + j;
                res.data[i][yj] = p_y;
                // 业绩id
                let y_id = "month" + j + "_id";
                res.data[i][y_id] = p_id;
              }
            }
            this.seenumber = this.searchList.size * this.searchList.page;
            this.datanumber = res.count;
            this.pagenumber = Math.ceil(res.count / this.searchList.size);
            this.tableData = res.data;
          } else {
            this.$message.error(res.msg);
          }
          this.loading = false;
        },
        (err) => {
          console.log(err);
          this.loading = false;
        }
      );
    },
    getdepartment() {
      this.$cmsapi.departmentList().then(
        (res) => {
          if (res.code == 0) {
            this.departmentList = res.data[0].childlist;
          } else {
            this.$message.error(res.msg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 搜索
    btnSearch() {
      this.loading = true;
      this.getData();
    },
    // 条件重置
    btnRefresh() {
      this.searchList = this.$options.data().searchList;
      this.searchList.year = this.yearsList[0].value;
      this.btnSearch();
    },
    // 表头汇总
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "汇总";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    // 新增编辑
    showEditer(obj) {
      this.titleSource = "新增销售目标";
      this.editorShow = true;
    },
    // 修改业绩对话框取消
    resetAch(formName) {
      this.$refs[formName].resetFields();
      this.achView = false;
      this.achData = this.$options.data().achData;
    },
    // 提交业绩对话数据
    submitAch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$cmsapi.completeSalesTarget(this.achData).then(
            (res) => {
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.achData = this.$options.data().achData;
                this.$refs[formName].resetFields();
                this.achView = false;
                this.loading = true;
                this.getData();
              } else {
                this.$message.error(res.msg);
              }
            },
            (err) => {
              console.log(err);
              this.loading = false;
            }
          );
          this.dialogGh = false;
          this.ghForm = this.$options.data().ghForm;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消
    resetGh(formName) {
      this.$refs[formName].resetFields();
      this.editorShow = false;
      this.ruleForm = this.$options.data().ruleForm;
    },
    // 提交
    submitGh(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.ruleForm.target = JSON.stringify(this.ruleForm.target);
          this.$cmsapi.saveSalesTarget(this.ruleForm).then(
            (res) => {
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.ruleForm = this.$options.data().ruleForm;
                this.$refs[formName].resetFields();
                this.editorShow = false;
                this.getData();
              } else {
                this.loading = false;
                this.$message.error(res.msg);
              }
            },
            (err) => {
              console.log(err);
              this.loading = false;
            }
          );
          this.dialogGh = false;
          this.ghForm = this.$options.data().ghForm;
        } else {
          console.log("error submit!!");
          this.$message({
            message: "请下拉填完必输选项进行操作！",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
/deep/ .el-table__footer-wrapper {
  position: absolute;
  top: 48px;
  left: 0;
}
/deep/ .el-table__body-wrapper {
  margin-top: 48px;
}
.ball {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.ball span {
  width: 95px;
}
.ball .el-input {
  flex-grow: 1;
  margin: 0 5px;
}
</style>